﻿#region usings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using InsuranceAdjuster.Web.Models;
using InsuranceAdjuster.Web.Services;
#endregion
namespace InsuranceAdjuster.OccasionallyConnected.Messages {
    public class SyncVehicleInformationMessage : Message {
        protected readonly Guid VehicleInformationGuid = new Guid("ECC5E4E3-E507-4F62-953A-E4AF21ED3F17");

        public SyncVehicleInformationMessage() {
            this.CacheRules = MessageDataSource.ServerOnly;
            GroupName = "Reference Sync";
            MessageName = "Sync Vehicle Information";
        }

        protected override void OnlineOperation() {
            MarkAsyncStarted();
            MarkAsyncStarted();
            GetDataService().GetVehicleInformationDelta(vehicles =>
            {
                VehicleInformation CurrentVehicleInformation = null;

                if (ResponseEntities.Any())
                    CurrentVehicleInformation = ResponseEntities["VehicleInformation"].Entity as VehicleInformation;
                else if (CurrentEntityManager.GetObjectStore().ContainsEntity(VehicleInformationGuid))
                    CurrentVehicleInformation = CurrentEntityManager.GetObjectStore().GetEntity<VehicleInformation>(VehicleInformationGuid);
                else 
                    CurrentVehicleInformation = new VehicleInformation();

                foreach (var Item in vehicles) {
                    if (Item.Value == EntitySyncOperation.Add)
                        CurrentVehicleInformation.Add(Item.Key as StandardVehicleImage);
                    else if (Item.Value == EntitySyncOperation.Delete)
                        CurrentVehicleInformation.Delete(Item.Key as StandardVehicleImage);
                    else if (Item.Value == EntitySyncOperation.Update)
                        CurrentVehicleInformation.Update(Item.Key as StandardVehicleImage);
                }

                ResponseEntities.Clear();
                ResponseEntities.Add("VehicleInformation", new MessageResult(Verb.Read, Origin.Server, CurrentVehicleInformation));
                MarkAsyncFinished();
            });
        }
        protected override List<MessageResult> CompileServerResults() {
            return this.ResponseEntities.Select(x => x.Value).ToList();
        }
    }
}
